package development;

import java.awt.Color;
import java.awt.Font;
import java.awt.SystemColor;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.sql.SQLException;

import javax.swing.DefaultComboBoxModel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.ScrollPaneConstants;
import javax.swing.UIManager;

import welcome.general.AboutTool;
import welcome.general.ChoosePerspective;
import DTO.Aspect;
import business.AspectFile;
import facade.Facade;
import general.AspectLibraryException;

public class PropertyCreationScreen {
	private static final String perspective = "Development Perspective";

	private static JFrame frmDevelopmentProperpety;
	private static PropertyCreationScreen window = null;

	private AboutTool aboutUs = null;

	private Facade facade = Facade.getInstance();
	
	/* Final components screen. */
	final JButton btnSave = new JButton("save");
	final JTextField txtNameAspect = new JTextField();
	final JTextArea tAreaIntertype = new JTextArea("");
	final JTextArea tAreaAdvicePointcut = new JTextArea("");
	final JComboBox<String> comboBox = new JComboBox<String>();
	final JMenuItem mntmClear = new JMenuItem("Clear");
	final JMenuItem mntmSave = new JMenuItem("Save");
	final JMenuItem mntmUsingControls = new JMenuItem("Help to use");
	
	JTextField tPropertyName;
	String[] propertiesNames = {""};

	public static JFrame getFrame() {
		return frmDevelopmentProperpety;
	}

	public static PropertyCreationScreen getWindow() {
		return window;
	}

	public PropertyCreationScreen() {
		aboutUs = new AboutTool();
		aboutUs.setVisible(false);

		initialize();
	}

	private void closeFrame(){
		frmDevelopmentProperpety.setVisible(false);
	}

	private void back(){
		closeFrame();
		ChoosePerspective.getChooseAppScreen().setVisible(true);
	}
	
	private String getPropertyName(){ 
		if(tPropertyName.getText()!=null && !tPropertyName.getText().equals("") && !tPropertyName.getText().equals(" ")){
			return tPropertyName.getText();
		}
		
		if(!comboBox.getSelectedItem().toString().equals(comboBox.getItemAt(0))){
			return comboBox.getSelectedItem().toString();
		}
		// TODO EXECACAOOO!!
		// TODO EXECACAOOO!!
		// TODO EXECACAOOO!!
		// TODO EXECACAOOO!!
		return null;
		
		// TODO clear e save
	}
	
	private boolean isNewProperty(){ 
		if(tPropertyName.getText()!=null && !tPropertyName.getText().equals("") && !tPropertyName.getText().equals(" ")){
			return true;
		}
		
		if(!comboBox.getSelectedItem().toString().equals(comboBox.getItemAt(0))){
			return false;
		}
		
		// TODO EXECACAOOO!!
		// TODO EXECACAOOO!!
		// TODO EXECACAOOO!!
		// TODO EXECACAOOO!!
		return false;
		
		// TODO clear e save
	}
	
	private void enableSaveButton(){
		if(tAreaIntertype.getText()!=null && tAreaIntertype.getText().length()>1 || tAreaAdvicePointcut.getText()!=null && tAreaAdvicePointcut.getText().length()>1){
			btnSave.setEnabled(true);
			mntmSave.setEnabled(true);
		}else{
			btnSave.setEnabled(false);
			mntmSave.setEnabled(false);
		}
	}
	
	private void clearScreen(){
		txtNameAspect.setText("");
		tAreaIntertype.setText("");
		tAreaAdvicePointcut.setText("");
		tPropertyName.setText("");
		
		btnSave.setEnabled(false);
		btnSave.setEnabled(false);
	}

	/* Facade calling methods */
	private void save(){
		try {
			//ajeitar parametros TODO
			AspectFile APGAR = facade.addAspect(new Aspect(txtNameAspect.getText(), isNewProperty(), getPropertyName(), tAreaIntertype.getText(), tAreaAdvicePointcut.getText()), propertiesNames); 
			
			// apagar e criar excecao!!
			if(APGAR == null){
				JOptionPane.showMessageDialog(null, "A error occurred in syntactic analysis.", "Validation Error", JOptionPane.ERROR_MESSAGE);
			}else{
				JOptionPane.showMessageDialog(null, "Aspect componentes were saved.", "Successful Operation", JOptionPane.INFORMATION_MESSAGE);
			}
			
			btnSave.setEnabled(false);
			mntmSave.setEnabled(false);

			
			clearScreen();
			//TODO colocar exc: nao tem id, tem coisas duplicadas, etc - ver utilizacao correta da gramatica ----------------------------------------------------
			//JOptionPane.showMessageDialog(null, e.getMessage(), e.getExceptionTitle() ,JOptionPane.ERROR_MESSAGE);
			
			//TODO ir pra tela inicial
		} catch (Exception e){
			System.out.println("EROO todo!");
			//JOptionPane.showMessageDialog(null, e.getStackTrace(), AspectLibraryException.INTERNAL_DB_ERROR, JOptionPane.ERROR_MESSAGE);
		}
	}

	private void showYesNoDialog(){
		int userResponse = JOptionPane.showConfirmDialog(null ,"Save alterations?","Closing perspective...",JOptionPane.YES_NO_OPTION); 
		if (userResponse == JOptionPane.YES_OPTION) { 
			save();
		}
	}

	private void initialize() {
		try{
			UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
			//UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
			//UIManager.setLookAndFeel("com.birosoft.liquid.LiquidLookAndFeel");
		}
		catch (Exception e) {
			System.out.println("erro look and feel");
		}
		/* Frame settings */
		frmDevelopmentProperpety = new JFrame();
		frmDevelopmentProperpety.getContentPane().setBackground(new Color(245, 245, 245));
		frmDevelopmentProperpety.setBounds(100, 100, 766, 680);
		frmDevelopmentProperpety.setResizable(false);
		frmDevelopmentProperpety.setIconImage(Toolkit.getDefaultToolkit().getImage("C:\\Users\\F. OMENA\\Dropbox\\Mestrado\\Projeto-Mestrado\\AspectLibrary\\Images\\logo\\logo3.png"));
		frmDevelopmentProperpety.setTitle("Aspect Library v. 1.0 - " + perspective);
		frmDevelopmentProperpety.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frmDevelopmentProperpety.setLocation(
				((Toolkit.getDefaultToolkit().getScreenSize().width / 2) - (frmDevelopmentProperpety
						.getWidth() / 2)), ((Toolkit.getDefaultToolkit()
								.getScreenSize().height / 2) - (frmDevelopmentProperpety.getHeight() / 2)));

		JSeparator separator = new JSeparator();
		separator.setForeground(Color.GRAY);

		/* Back button. */
		JButton bntBack = new JButton("< back");
		bntBack.setBackground(SystemColor.controlHighlight);

		/* Scroll pane. */
		JScrollPane scrGrammar = new JScrollPane();
		scrGrammar.setToolTipText("");
		scrGrammar.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
		scrGrammar.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

		/* Save button. */
		btnSave.setEnabled(false);
		btnSave.setIcon(new ImageIcon("C:\\Users\\F. OMENA\\Dropbox\\Mestrado\\Projeto-Mestrado\\AspectLibrary\\Images\\buttons\\save.png"));
		btnSave.setBackground(SystemColor.controlHighlight);

		/* Label aspect name. */
		JLabel lblAspectName = new JLabel("Aspect Name");
		lblAspectName.setFont(new Font("Arial", Font.PLAIN, 12));

		/* Label step name. */
		JLabel lblStep = new JLabel("Step 1 of 1");
		lblStep.setFont(new Font("Times New Roman", Font.PLAIN, 12));
		
		/* Label intertype name. */
		JLabel lblIntertype = new JLabel("Intertypes");
		lblIntertype.setFont(new Font("Arial", Font.PLAIN, 12));
		
		/* Label advice and pointcut name. */
		JLabel lblAdvicesPointcuts = new JLabel("Advices and Pointcuts");
		lblAdvicesPointcuts.setFont(new Font("Arial", Font.PLAIN, 12));
		
		/* JTextField aspect name. */
		txtNameAspect.setColumns(10);

		/* Text area intertype component. */
		tAreaIntertype.setTabSize(5);
		tAreaIntertype.setColumns(5);
		tAreaIntertype.setRows(5);
		tAreaIntertype.setEditable(true);

		/* Text area advice and pointcut component. */
		tAreaAdvicePointcut.setRows(10);
		tAreaAdvicePointcut.setEditable(true);
		tAreaAdvicePointcut.setColumns(10);
		
		/* TextField for new property associated. */
		tPropertyName = new JTextField();
		tPropertyName.setColumns(10);
		
		/* Combobox component. */
		comboBox.setFont(new Font("Tahoma", Font.PLAIN, 10));
		
		try {
			propertiesNames = facade.getPropertiesNames();
		} catch (SQLException e){
			JOptionPane.showMessageDialog(null, e.getStackTrace(), AspectLibraryException.INTERNAL_DB_ERROR, JOptionPane.ERROR_MESSAGE);
		}
		
		comboBox.setModel(new DefaultComboBoxModel(propertiesNames));
		comboBox.setBackground(new Color(245, 245, 245));
		
		/* Label of combobox. */
		JLabel lblOrSetA = new JLabel("or set a new");
		lblOrSetA.setFont(new Font("Arial", Font.PLAIN, 10));
		
		/* Label of property associated. */
		JLabel lblPropertyAssociated = new JLabel("Associated Property");
		lblPropertyAssociated.setFont(new Font("Arial", Font.PLAIN, 12));

		/* Menu bar */
		JMenuBar menuBar = new JMenuBar();
		frmDevelopmentProperpety.setJMenuBar(menuBar);

		/* Menu - File: */
		JMenu mnFile = new JMenu("File");
		mnFile.setMnemonic('f');
		mnFile.setBackground(UIManager.getColor("CheckBox.highlight"));
		menuBar.add(mnFile);

		/* Clear menu item. */
		mntmClear.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK));
		mntmClear.setIcon(new ImageIcon("C:\\Users\\F. OMENA\\Dropbox\\Mestrado\\Projeto-Mestrado\\AspectLibrary\\Images\\buttons\\clear_gray.png"));
		mnFile.add(mntmClear);
		mntmClear.setEnabled(false);

		/* Save menu item. */
		mntmSave.setEnabled(false);
		mntmSave.setBackground(SystemColor.control);
		mntmSave.setIcon(new ImageIcon("C:\\Users\\F. OMENA\\Dropbox\\Mestrado\\Projeto-Mestrado\\AspectLibrary\\Images\\buttons\\save.png"));
		mnFile.add(mntmSave);

		/* Refresh menu item and separator. */
		JSeparator separator_2 = new JSeparator();
		mnFile.add(separator_2);

		/* Exit menu item. */
		JMenuItem mntmExit = new JMenuItem("Quit");
		mntmExit.setIcon(new ImageIcon("C:\\Users\\F. OMENA\\Dropbox\\Mestrado\\Projeto-Mestrado\\AspectLibrary\\Images\\buttons\\exit_white.png"));
		mntmExit.setBackground(SystemColor.control);
		mntmExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, InputEvent.CTRL_MASK));
		mnFile.add(mntmExit);

		/* Menu - Help: */
		JMenu mnHelp = new JMenu("Help");
		mnHelp.setMnemonic('h');
		menuBar.add(mnHelp);

		/* Help to use menu item. */
		mntmUsingControls.setBackground(SystemColor.menu);
		mnHelp.add(mntmUsingControls);
		
		/* About menu item. */
		JMenuItem mntmAbout_1 = new JMenuItem("About");
		mntmAbout_1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0));
		mnHelp.add(mntmAbout_1);
		mntmAbout_1.setBackground(SystemColor.control);
		mntmAbout_1.setIcon(new ImageIcon("C:\\Users\\F. OMENA\\Dropbox\\Mestrado\\Projeto-Mestrado\\AspectLibrary\\Images\\buttons\\about_gray.png"));


		/* -------------------- Events -------------------- */

		/* About button event. */
		mntmAbout_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				aboutUs.setVisible(true);	
			}
		});

		/* Exit buttons event. */
		mntmExit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(btnSave.isEnabled() || mntmSave.isEnabled()){
					showYesNoDialog();
				}
				System.exit(0);
			}
		});

		/* Back button event. */
		bntBack.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				/* Its not enable when the aspect was saved. */
				if(btnSave.isEnabled() || mntmSave.isEnabled()){
					showYesNoDialog();
				}
				back();
			}
		});

		/* Save buttons event. */
		btnSave.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				save();
			}
		});
		mntmSave.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				save();
			}
		});

		/* Clear event */
		mntmClear.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				clearScreen();
			}
		});
		
		
		/* Keyboard event on intertype text area and advicePointcut text area. */
		tAreaIntertype.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent arg0) {
				enableSaveButton();
			}
			@Override
			public void keyTyped(KeyEvent e) {
				enableSaveButton();
			}
		});

		/* Layout */
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		scrollPane.setToolTipText("");
		scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);

		scrollPane.setViewportView(tAreaAdvicePointcut);
		scrGrammar.setViewportView(tAreaIntertype);
		
		GroupLayout groupLayout = new GroupLayout(frmDevelopmentProperpety.getContentPane());
		groupLayout.setHorizontalGroup(
			groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup()
					.addContainerGap()
					.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
						.addGroup(groupLayout.createSequentialGroup()
							.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
								.addComponent(separator, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
								.addGroup(groupLayout.createSequentialGroup()
									.addComponent(lblAspectName)
									.addGap(611)
									.addComponent(lblStep))
								.addComponent(lblIntertype, GroupLayout.PREFERRED_SIZE, 74, GroupLayout.PREFERRED_SIZE)
								.addComponent(scrGrammar, GroupLayout.PREFERRED_SIZE, 738, GroupLayout.PREFERRED_SIZE)
								.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING, false)
									.addComponent(txtNameAspect, Alignment.LEADING)
									.addGroup(Alignment.LEADING, groupLayout.createSequentialGroup()
										.addComponent(comboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
										.addPreferredGap(ComponentPlacement.UNRELATED)
										.addComponent(lblOrSetA)
										.addPreferredGap(ComponentPlacement.RELATED)
										.addComponent(tPropertyName, GroupLayout.PREFERRED_SIZE, 160, GroupLayout.PREFERRED_SIZE))))
							.addContainerGap(12, Short.MAX_VALUE))
						.addGroup(groupLayout.createSequentialGroup()
							.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
								.addComponent(lblAdvicesPointcuts)
								.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 738, GroupLayout.PREFERRED_SIZE))
							.addContainerGap(12, Short.MAX_VALUE))
						.addGroup(groupLayout.createSequentialGroup()
							.addComponent(bntBack)
							.addPreferredGap(ComponentPlacement.RELATED, 598, Short.MAX_VALUE)
							.addComponent(btnSave)
							.addGap(12))
						.addComponent(lblPropertyAssociated)))
		);
		groupLayout.setVerticalGroup(
			groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup()
					.addGap(14)
					.addComponent(separator, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
					.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblAspectName)
						.addComponent(lblStep))
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(txtNameAspect, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
					.addGap(17)
					.addComponent(lblPropertyAssociated, GroupLayout.PREFERRED_SIZE, 15, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
						.addComponent(comboBox, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE)
						.addComponent(lblOrSetA, GroupLayout.PREFERRED_SIZE, 15, GroupLayout.PREFERRED_SIZE)
						.addComponent(tPropertyName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addGap(18)
					.addComponent(lblIntertype)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(scrGrammar, GroupLayout.PREFERRED_SIZE, 203, GroupLayout.PREFERRED_SIZE)
					.addGap(18)
					.addComponent(lblAdvicesPointcuts)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
					.addGap(18)
					.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
						.addComponent(bntBack)
						.addComponent(btnSave))
					.addGap(81))
		);
		frmDevelopmentProperpety.getContentPane().setLayout(groupLayout);
	}
}
